package com.softao.ming.gde.internal.core.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.softao.ming.gde.core.model.IBundlePluginFile;
import com.softao.ming.gde.core.model.IExtension;
import com.softao.ming.gde.internal.core.util.XmlHelper;

/**
 * plugin.xml file.
 */
public class BundlePluginImpl implements IBundlePluginFile {
	private final Map<String, List<IExtension>> mExtensions;
	private final String mContent;
	
	/**
	 * @param inputStream 
	 * @throws IOException 
	 */
	public BundlePluginImpl(final InputStream inputStream) throws IOException {
		mExtensions = new HashMap<String, List<IExtension>>();
		InputStreamReader isr = new InputStreamReader(inputStream);
		BufferedReader reader = new BufferedReader(isr);
		
		StringBuilder sbPlugin = new StringBuilder();
		
		String line = reader.readLine();
		while (line != null) {
			sbPlugin.append(line);
			sbPlugin.append("\n");
			
			line = reader.readLine();
		}
		
		mContent = sbPlugin.toString();
		
		Document document = XmlHelper.loadDocument(mContent);
		Element root = document.getDocumentElement();
		Iterator<Element> children = XmlHelper.getChildren(root, "extension");
		while (children.hasNext()) {
			Element child = children.next();
			String extPointid = child.getAttribute("point");
			IExtension extension = new ExtensionImpl(extPointid, child);
			if (!mExtensions.containsKey(extPointid)) {
				mExtensions.put(extPointid, new ArrayList<IExtension>());
			}
			List<IExtension> list = mExtensions.get(extPointid);
			list.add(extension);
		}
		
	}
	
	/**
	 * @return the extensions
	 */
	public Map<String, List<IExtension>> getExtensions() {
		return mExtensions;
	}
	
	/**
	 * @return the content
	 */
	public String getContent() {
		return mContent;
	}

	@Override
	public List<String> getExtensionPoints() {
		List<String> result = new ArrayList<String>();
		
		result.addAll(mExtensions.keySet());
		
		return result;
	}

	@Override
	public List<IExtension> getExtensions(String extensionPointId) {
		List<IExtension> result = new ArrayList<IExtension>();
		
		if (mExtensions.containsKey(extensionPointId)) {
			List<IExtension> list = mExtensions.get(extensionPointId);
			result.addAll(list);
		}
		
		return result;
	}
}
